package com.aisb.manage;

import com.aisb.core.BaseController;
import com.aisb.core.InitParam;
import com.aisb.core.Result;
import com.aisb.core.util.DateUtil;
import com.aisb.core.util.file.ExcelUtils;
import com.aisb.core.log.LogOper;
import com.aisb.core.log.LogVisit;
import com.github.pagehelper.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/manage/user")
public class UserController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Autowired
    private AuthService authService;


    @RequestMapping(value = "/index")
    @RequiresPermissions("/manage/user/index")
    @LogVisit("用户管理列表")
    public String index(Model model) {
        return "manage/user";
    }

    @RequestMapping(value = "/add/index")
    @RequiresPermissions("/manage/user/add")
    @LogVisit("用户管理，用户新增")
    public String indexAdd(Model model) {
        return "manage/user_add";
    }

    @RequestMapping(value = "/view/{userId}")
    @RequiresPermissions("/manage/user/index")
    @LogVisit("用户管理，用户查看")
    public String indexView(Model model, @PathVariable String userId) {
        Map param = new HashMap();
        param.put("userId", userId);

        Object o = userService.userOne(userId);
        model.addAttribute("userInfo", o);

        // 查询角色
        List roleIds = new ArrayList();
        List<Map> raList = authService.rolesForUser(param);
        if (null != raList) {
            for (Map m : raList) {
                roleIds.add(m.get("roleId"));
            }
        }
        model.addAttribute("roleIds", roleIds);

        return "manage/user_view";
    }

    @RequestMapping(value = "/modify/{userId}")
    @RequiresPermissions("/manage/user/modify")
    @LogVisit("用户管理，用户修改")
    public String indexModify(Model model, @PathVariable String userId) {
        Map param = new HashMap();
        param.put("userId", userId);

        Object o = userService.userOne(userId);
        model.addAttribute("userInfo", o);

        // 查询角色
        List roleIds = new ArrayList();
        List<Map> raList = authService.rolesForUser(param);
        if (null != raList) {
            for (Map m : raList) {
                roleIds.add(m.get("roleId"));
            }
        }
        model.addAttribute("roleIds", roleIds);

        return "manage/user_modify";
    }


    @RequestMapping(value = "/list")
    @ResponseBody
    public Result list(@RequestParam Map param) {
        String pageNumStr = (String) param.get("pageNum");
        String pageSizeStr = (String) param.get("pageSize");

        Integer pageNum = Integer.parseInt(pageNumStr);
        Integer pageSize = Integer.parseInt(pageSizeStr);

        Page page = userService.userList(param, pageNum, pageSize);

        Map r = new HashMap();
        r.put("total", page.getTotal());
        r.put("rows", page.getResult());

        Subject currentUser = SecurityUtils.getSubject();
        boolean addFlag = currentUser.isPermitted("/manage/user/add");
        boolean modifyFlag = currentUser.isPermitted("/manage/user/modify");
        boolean deleteFlag = currentUser.isPermitted("/manage/user/delete");
        boolean uploadFlag = currentUser.isPermitted("/manage/user/upload");
        boolean downloadFlag = currentUser.isPermitted("/manage/user/download");
        r.put("addFlag", addFlag);
        r.put("modifyFlag", modifyFlag);
        r.put("deleteFlag", deleteFlag);
        r.put("uploadFlag", uploadFlag);
        r.put("downloadFlag", downloadFlag);

        return new Result(true, r);
    }

    @RequestMapping(value = "/add")
    @RequiresPermissions("/manage/user/add")
    @ResponseBody
    public Result add(@RequestParam Map param) {
        int result = userService.userAdd(param);

        return new Result(true, result);
    }

    @RequestMapping(value = "/checkexist")
    @RequiresPermissions("/manage/user/add")
    @ResponseBody
    public Map checkExist(@RequestParam Map param) {
        Map result = new HashMap();

        Object o = userService.userOne(param);
        if (null == o) {
            result.put("valid", true);
        } else {
            result.put("valid", false);
        }

        return result;
    }

    @RequestMapping(value = "/modify")
    @RequiresPermissions("/manage/user/modify")
    @ResponseBody
    @LogOper("用户管理，用户修改")
    public Result modify(@RequestParam Map param) {
        int result = userService.userModify(param, true);

        return new Result(true, result);
    }

    @RequestMapping(value = "/delete")
    @RequiresPermissions("/manage/user/delete")
    @ResponseBody
    @LogOper("用户管理，用户删除")
    public Result delete(@RequestParam Map param) {
        int result = userService.userDelete(param);

        return new Result(true, result);
    }

    @RequestMapping(value = "/pwdreset")
    @RequiresPermissions("/manage/modify")
    @ResponseBody
    @LogOper("用户管理，密码重置")
    public Result pwdReset(@RequestParam Map param) {
        param.put("userPwd", InitParam.DEFAULT_PASSWORD);
        int result = userService.userModify(param, false);

        return new Result(true, result);
    }

    @RequestMapping(value = "/pwdmodify")
    @ResponseBody
    @LogOper("用户管理，密码修改")
    public Result pwdModify(@RequestParam Map param) {
        int result = userService.userModify(param, false);

        return new Result(true, result);
    }

    @RequestMapping(value = "/online")
    @RequiresPermissions("/manage/user/modify")
    @ResponseBody
    @LogOper("用户管理，批量上线")
    public Result online(@RequestParam Map param) {
        param.put("status", "1");
        int result = userService.userModify(param, false);

        return new Result(true, result);
    }

    @RequestMapping(value = "/offline")
    @RequiresPermissions("/manage/user/modify")
    @ResponseBody
    @LogOper("用户管理，批量下线")
    public Result offline(@RequestParam Map param) {
        param.put("status", "0");
        int result = userService.userModify(param, false);

        return new Result(true, result);
    }

    @RequestMapping(value = "/roles/{userId}")
    @ResponseBody
    public Result roles(@RequestParam Map param, @PathVariable String userId) {
        Map r = new HashMap();

        param.put("userId", userId);

        List rList = authService.roleList();
        List aList = authService.areaList();
        List raList = authService.rolesForUser(param);

        r.put("roleTotalNum", rList.size());

        for (Object m : aList) {
            ((Map) m).put("nocheck", "true");
        }

        rList.addAll(authService.dealAreaTree(rList, aList));

        Map raMap = new HashMap();
        if (null != raList) {
            for (Object m : raList) {
                String roleId = (String) ((Map) m).get("roleId");
                String roleName = (String) ((Map) m).get("roleName");
                raMap.put(roleId, roleName);
            }
        }

        for (Object m : rList) {
            String roleId = (String) ((Map) m).get("id");
            if (raMap.containsKey(roleId)) {
                ((Map) m).put("checked", true);
            }
        }


        r.put("roles", rList);
        r.put("roleSelNum", raMap.size());

        return new Result(true, r);
    }

    @RequestMapping(value = "/export")
    @RequiresPermissions("/manage/user/download")
    @ResponseBody
    @LogOper("用户管理，数据导出")
    public Result export(@RequestParam Map param) {
        List<Map> rList = userService.userList(param);

        String fileName = "用户_" + DateUtil.getInstance().getToday("yyyyMMddHmmsss") + ".xls";
        boolean flag = ExcelUtils.getInstance().createExcel(fileName, rList);

        return new Result(flag, fileName);
    }
}
